﻿using System;
using System.Linq;
using System.Threading;
using Nutilities.Threading;

namespace PumpStationClient
{
    public class Simulator : ThreadClass
    {
        private readonly PumpStation _station;

        public Simulator(PumpStation station)
        {
            _station = station;
        }

        protected override void Run()
        {
            Console.WriteLine("Simulator running...");
            Random rand = new Random();
            // 0 m/3
            // 1000 m/3
            // 2000 m/3
            // 3000 m/3
            double wl = 500.0;
            int secondsPassed = 1;
            while (Running)
            {
                double totalCapacity = _station.Pumps.Where(pump => pump.Running).Sum(pump => pump.Capacity);
                double capacityPerSecond = totalCapacity / 60 / 60;

                wl += rand.NextDouble() * 20;
                if (wl > 3999.9)
                {
                    wl = 3999.9;
                }
                wl -= capacityPerSecond;
                if (wl < 0.0)
                {
                    wl = 0.0;
                }

                if (secondsPassed < 5)
                {
                    secondsPassed++;
                }
                else
                {
                    _station.Waterlevel = (int) Math.Floor(wl / 1000);
                    secondsPassed = 1;
                    Console.WriteLine("Waterlevel: " + wl);
                }
                Thread.Sleep(1000);
            }
        }
    }
}
